import React, { useState, useEffect } from "react";
import { View, StyleSheet, Dimensions, Text, Image, Clipboard, TextInput, TouchableOpacity } from "react-native";
import { Button, Icon } from "@rneui/themed";
import web3Utils from 'web3-utils'
import api from "@/request/api";
import Toast from 'react-native-simple-toast'
import LinearGradinet from 'react-native-linear-gradient';
import { useSelector, useDispatch } from "react-redux";
import IconNavBar from '@/components/IconNavBar'
import ModalMenu from "@/components/ModalMenu";
import ScanModal from '@/components/ScanModal'
import Loading from "@/components/LoadingModal";
import { sectokenCommonCenterProps } from '@/config/navigatorProps'
import { PayWithArray } from '@/config/config'
import CommonContext from '@/utils/createContext'
import { guid } from "@/utils/util";

const { width, scale } = Dimensions.get('window')
const ratio = width * scale / 1080

const SectokenSendInfo = (props) => {

    const dispatch = useDispatch()
    const [menuVisible, setMenuVisible] = useState(false)
    const [loadingVisible, setLoadingVisible] = useState(false)
    const [cameraVisible, setCameraVisible] = useState(false)
    const [recipientAddress, setRecipientAddress] = useState('')
    const [amount, setAmount] = useState(undefined)
    const [profileImg, setProfileImg] = useState('')
    const [error, setError] = useState(false);
    const selectedSafeWallet = useSelector((state) => state.sectokenMainReducer.selectedSafeWallet || {});
    const selectedSafeAsset = useSelector((state) => state.sectokenMainReducer.selectedSafeAsset || {});

    useEffect(() => {
        let arr = Object.keys(PayWithArray)
        let random = Math.floor(Math.random() * 3)
        let profileImg = arr[random]
        setProfileImg(profileImg)
    }, [])

    useEffect(() => {
        if (recipientAddress && recipientAddress.length > 0) {
            checkAddress()
        }
    }, [recipientAddress])

    const checkAddress = () => {
        //1.检查地址的有效性，调用web3.utils.toChecksumAddress
        let result = web3Utils.checkAddressChecksum(recipientAddress)
        if (result) {
            setLoadingVisible(true)
            //2.调用接口查询地址的类型，合约地址或普通地址
            api.check_address(recipientAddress).then(res => {
                if (res.result === '0x') {
                    setError(true)
                    Toast.showWithGravity(
                        'This address is invalid!',
                        Toast.SHORT,
                        Toast.CENTER)
                }
                setLoadingVisible(false)
            }).catch(() => {
                setError(true)
                Toast.showWithGravity(
                    'This address is invalid!',
                    Toast.SHORT,
                    Toast.CENTER)
                setLoadingVisible(false)
            })
        } else {
            setError(true)
            Toast.showWithGravity(
                'This address is invalid!',
                Toast.SHORT,
                Toast.CENTER)
        }
    }

    const handlePressLeft = () => {
        props.navigation.goBack()
    }

    const handlePressOpenMenu = () => {
        setMenuVisible(true)
    }

    const handlePressPaste = async () => {
        let content = await Clipboard.getString();
        if (content && content.length > 0) {
            setRecipientAddress(content)
        }
        setMenuVisible(false)
    }

    const handlePressScan = () => {
        setMenuVisible(false)
        setCameraVisible(true)
    }

    const handleReadCode = (result) => {
        const { data } = result;
        if (data && data.length > 0) {
            setRecipientAddress(data)
        }
        setCameraVisible(false)
    }

    const handlePressMax = () => {
        setAmount(selectedSafeAsset.balance || 0)
    }

    const handlePressReview = () => {
        if (!error && recipientAddress && recipientAddress.length > 0) {
            if (parseFloat(selectedSafeAsset.balance) <= 0 || parseFloat(amount) > parseFloat(selectedSafeAsset.balance)) {
                Toast.showWithGravity(
                    'insufficient funds!',
                    Toast.SHORT,
                    Toast.CENTER)
            } else {
                let obj = {
                    id: guid(),
                    amount,
                    address: recipientAddress,
                    label: 'recipient1',
                    profileImg
                }
                dispatch({ type: "setSendData", value: obj });
                props.navigation.navigate('safe-send-review')
            }
        }
    }

    return (
        <View style={{ ...styles.container, backgroundColor: menuVisible ? '#000000' : '#FFFFFF', opacity: menuVisible ? 0.2 : 1 }}>
            <IconNavBar {...props} {...sectokenCommonCenterProps} {...{ title: 'Send' }} handlePressLeft={handlePressLeft} />
            <View style={styles.bodyContent}>
                <View style={{ alignItems: 'center' }}>
                    <View style={styles.content1}>
                        <Image source={PayWithArray[selectedSafeWallet.profileImg]} style={styles.img1} />
                        <View style={{ justifyContent: 'center', marginLeft: 14 * ratio }}>
                            <Text style={{ ...styles.title1 }}>{selectedSafeWallet.label}</Text>
                            <Text style={{ ...styles.title3, width: 174 * ratio }}
                                ellipsizeMode='middle' numberOfLines={1}>
                                {selectedSafeWallet.address}
                            </Text>
                        </View>
                    </View>
                </View>
                <Text style={{ ...styles.title3, marginTop: 20 * ratio, marginLeft: 15 * ratio }}>Collection address</Text>
                <View style={{ alignItems: 'center', marginTop: 11 * ratio }}>
                    <View style={{ ...styles.content2, justifyContent: 'space-between' }}>
                        <Image source={PayWithArray[profileImg]} style={{ ...styles.img2, marginLeft: 7 * ratio }} />
                        <Text numberOfLines={1} ellipsizeMode={recipientAddress ? 'middle' : 'clip'}
                            style={{ ...styles.title2, width: 230 * ratio, marginLeft: 7 * ratio }}>
                            {recipientAddress ? recipientAddress : 'Recipient’s address'}
                        </Text>
                        <Icon style={{ marginRight: 15 * ratio }} type='antdesign' name='ellipsis1' color='#979797' size={30} onPress={handlePressOpenMenu} />
                    </View>
                </View>
                <View style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'space-between', marginTop: 11 * ratio }}>
                    <View style={{ flexDirection: 'row' }}>
                        <Text style={{ ...styles.title3, marginLeft: 15 * ratio }}>Total Assets:</Text>
                        <Text style={{ ...styles.title3, color: '#2C2C2C' }}>{selectedSafeAsset.balance} {selectedSafeAsset.tokenInfo.symbol?.toUpperCase()}</Text>
                    </View>
                    <Button type="clear" onPress={handlePressMax}>
                        <Text style={{ ...styles.title3, color: '#0A6EEB', marginRight: 15 * ratio }}>Send Max</Text>
                    </Button>
                </View>
                <View style={{ alignItems: 'center', marginTop: 11 * ratio }}>
                    <View style={styles.content2}>
                        <Image source={{ uri: selectedSafeAsset.tokenInfo.logoUri }} style={styles.img2} />
                        <TextInput
                            style={{ ...styles.title3, color: '#2C2C2C', flex: 1, marginLeft: 6 * ratio }}
                            placeholderTextColor='#898989'
                            placeholder='Amount'
                            onChangeText={text => setAmount(text)}
                            value={amount && amount.toString()}
                            keyboardType='numeric' />
                    </View>
                </View>
                <View style={{ flex: 1, justifyContent: 'flex-end', alignItems: 'center', marginBottom: 24 * ratio }}>
                    <TouchableOpacity onPress={handlePressReview}>
                        <LinearGradinet colors={['#0EBBF8', '#0069F6']} start={{ x: 0, y: 0 }} end={{ x: 1, y: 0 }} style={styles.button}>
                            <Text style={{ ...styles.title1, color: '#FFFFFF', textAlign: 'center' }}>Review</Text>
                        </LinearGradinet>
                    </TouchableOpacity>
                </View>
            </View>
            <CommonContext.Provider value={{ modalVisible: menuVisible, setModalVisible: setMenuVisible, handlePressPaste, handlePressScan }}>
                <ModalMenu />
            </CommonContext.Provider>
            <CommonContext.Provider value={{ modalVisible: cameraVisible, setModalVisible: setCameraVisible, handleReadCode }}>
                <ScanModal />
            </CommonContext.Provider>
            {loadingVisible && <Loading visible={loadingVisible} />}
        </View>
    )
}

const styles = StyleSheet.create({
    container: {
        flex: 1
    },
    bodyContent: {
        flex: 1,
        marginTop: 10 * ratio
    },
    content1: {
        width: 330 * ratio,
        height: 56 * ratio,
        backgroundColor: '#F7F7F7',
        flexDirection: 'row',
        alignItems: 'center'
    },
    content2: {
        width: 330 * ratio,
        height: 44 * ratio,
        backgroundColor: '#F7F7F7',
        flexDirection: 'row',
        alignItems: 'center'
    },
    img1: {
        width: 40 * ratio,
        height: 40 * ratio,
        marginLeft: 10 * ratio
    },
    img2: {
        width: 25 * ratio,
        height: 25 * ratio,
        marginLeft: 7 * ratio
    },
    title1: {
        fontSize: 16,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#2C2C2C',
        lineHeight: 24
    },
    title2: {
        fontSize: 14,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#898989',
        lineHeight: 21
    },
    title3: {
        fontSize: 12,
        fontFamily: 'SourceHanSansCN-Medium, SourceHanSansCN',
        fontWeight: '500',
        color: '#606060',
        lineHeight: 18
    },
    button: {
        width: 310 * ratio,
        height: 50,
        borderRadius: 28,
        justifyContent: 'center'
    }
})
export default SectokenSendInfo